// src/services/analyticsService.ts
import api from './api';

interface AnalyticsEvent {
  name: string;
  properties?: Record<string, any>;
  timestamp?: number;
}

interface UserProperties {
  userId?: string;
  email?: string;
  subscription?: string;
  [key: string]: any;
}

class AnalyticsService {
  private queue: AnalyticsEvent[] = [];
  private batchSize = 20;
  private flushInterval = 30000; // 30秒
  private flushTimer: NodeJS.Timeout | null = null;

  constructor() {
    // 定期发送事件
    this.startFlushTimer();
  }

  // 记录事件
  track(eventName: string, properties?: Record<string, any>): void {
    const event: AnalyticsEvent = {
      name: eventName,
      properties,
      timestamp: Date.now(),
    };

    this.queue.push(event);
    console.log('[Analytics] Event tracked:', eventName, properties);

    // 如果队列达到批量大小，立即发送
    if (this.queue.length >= this.batchSize) {
      this.flush();
    }
  }

  // 设置用户属性
  async setUserProperties(properties: UserProperties): Promise<void> {
    try {
      await api.post('/app/analytics/user', properties);
      console.log('[Analytics] User properties set:', properties);
    } catch (error) {
      console.error('[Analytics] Set user properties error:', error);
    }
  }

  // 记录屏幕浏览
  trackScreen(screenName: string, properties?: Record<string, any>): void {
    this.track('screen_view', {
      screen_name: screenName,
      ...properties,
    });
  }

  // 记录用户行为
  trackUserAction(action: string, category: string, label?: string, value?: number): void {
    this.track('user_action', {
      action,
      category,
      label,
      value,
    });
  }

  // 记录错误
  trackError(error: Error, fatal = false): void {
    this.track('error', {
      message: error.message,
      stack: error.stack,
      fatal,
    });
  }

  // 记录性能
  trackPerformance(metric: string, value: number, unit = 'ms'): void {
    this.track('performance', {
      metric,
      value,
      unit,
    });
  }

  // 发送队列中的事件
  private async flush(): Promise<void> {
    if (this.queue.length === 0) return;

    const events = [...this.queue];
    this.queue = [];

    try {
      await api.post('/app/analytics/events', { events });
      console.log(`[Analytics] Flushed ${events.length} events`);
    } catch (error) {
      console.error('[Analytics] Flush error:', error);
      // 失败的事件重新加入队列
      this.queue.unshift(...events);
    }
  }

  // 开始定时发送
  private startFlushTimer(): void {
    this.flushTimer = setInterval(() => {
      this.flush();
    }, this.flushInterval);
  }

  // 停止定时发送
  private stopFlushTimer(): void {
    if (this.flushTimer) {
      clearInterval(this.flushTimer);
      this.flushTimer = null;
    }
  }

  // 清理
  cleanup(): void {
    this.stopFlushTimer();
    this.flush();
  }
}

export default new AnalyticsService();